'use strict';
const db = uniCloud.database()
const usersCollection = db.collection('users')

exports.main = async (event, context) => {
	const { userInfo } = event
	
	try {
		if (!userInfo.username) {
			return {
				code: -1,
				msg: '用户名不能为空'
			}
		}
		
		if (!userInfo.mobile) {
			return {
				code: -1,
				msg: '手机号不能为空'
			}
		}
		
		if (!userInfo.password) {
			return {
				code: -1,
				msg: '密码不能为空'
			}
		}
		
		// 检查用户名是否已存在
		const usernameCheck = await usersCollection.where({
			username: userInfo.username
		}).count()
		
		if (usernameCheck.total > 0) {
			return {
				code: -1,
				msg: '用户名已存在'
			}
		}
		
		// 检查手机号是否已存在
		const mobileCheck = await usersCollection.where({
			mobile: userInfo.mobile
		}).count()
		
		if (mobileCheck.total > 0) {
			return {
				code: -1,
				msg: '手机号已存在'
			}
		}
		
		// 添加用户
		const res = await usersCollection.add({
			username: userInfo.username,
			mobile: userInfo.mobile,
			avatar: userInfo.avatar || '',
			password: userInfo.password,
			createTime: Date.now()
		})
		
		return {
			code: 0,
			msg: '添加成功',
			data: {
				_id: res.id
			}
		}
	} catch (e) {
		console.error('添加用户失败', e)
		return {
			code: -1,
			msg: '添加失败',
			error: e
		}
	}
} 